package net.opentsdb.utils;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;

/**
 * @Author hujf
 * @Date 2021/12/31 14:46
 * @Description 自定义一个json 处理 把 map 转成json
 */
public class JSON {

    private static ObjectMapper jsonMapper = new ObjectMapper();

    public static final byte[] serializeToBytes(Object o){
        if(o==null){
            throw new IllegalArgumentException("o was null");
        }else{
            cn.hutool.json.JSON parse = JSONUtil.parse(o);
            return parse.toString().getBytes(StandardCharsets.UTF_8);
        }
    }

    public static final <T> T parseToObject(String json , Class<T> pojo) {
        if(json==null ||json.isEmpty()){
            throw new IllegalArgumentException("is empty");
        }
        try {
            return jsonMapper.readValue(json,pojo);
        }catch (Exception e){
            throw new IllegalArgumentException(e);
        }
    }

    public static final <T> T parseToObject(String json , TypeReference<T> pojo) {
        if(json==null ||json.isEmpty()){
            throw new IllegalArgumentException("is empty");
        }
        try {
            return jsonMapper.readValue(json,pojo);
        }catch (Exception e){
            throw new IllegalArgumentException(e);
        }
    }
}
